//=============================================================================
// XBus 
//-----------------------------------------------------------------------------
// File        : consumer.c
// Description : 
// Author      : Ismail Sabry
// Date        : 1/30/2009
//=============================================================================
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>

#include <xbus_interface.h>

int get_option(int argc, char **argv, char *xbus_name, int *xbus_module );

#define BUF_SIZE      1024

static int alive=1;

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void catch_signal(int sig)
{
  alive = 0;
  printf("\nSTOP (sig %d) \n", sig);
  fflush(stdout);
}

//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
int main (int argc, char **argv)
{
  char               xbux_name[XBUS_SIZE_NAME];
  int                xbus_id;
  t_XBUS_interface   interface;
  int                ret, index;
  unsigned char      buf[BUF_SIZE];
  t_XBUS_cell        *cell;
  
#if 1
  if( get_option(argc, argv, xbux_name, &xbus_id) == -1)
    return -1;
#else
  snprintf(xbus_name, XBUS_SIZE_NAME-1, "test");  
  xbus_id = 1;
#endif

  signal(SIGINT,  catch_signal);
  signal(SIGQUIT, catch_signal);
  signal(SIGTERM, catch_signal);
  
  if( XBUS_link(&interface, XBUS_CONSUMER, xbux_name, xbus_id) == -1)
    return -1;
  
  index=0;
  while(alive) {
    cell = interface.cell;
    ret = XBUS_read(&interface, buf, BUF_SIZE);
    if(ret > 0) {
      printf("(%u/%u) read [%p](%d)\n", 
	     interface.riter, interface.rcell,
	     cell, (int)buf[0]);
    } else {
      printf("%d", ret);
    }
    fflush(stdout);
    sleep(1);
    index++;
  }

  XBUS_unlink(&interface);

  return 0;

}
